import 'package:flutter_reactive_value/flutter_reactive_value.dart';
import 'package:kudos/core/state/topic/kite_topic_entity.dart';
import 'kite_topic_discussion_entity.dart';
import 'kite_topic_like_entity.dart';
import '../person/persona_session_controller.dart';

/// 风筝话题讨论控制器 - 使用非常规命名避免重复识别
class KiteTopicController {
  static final KiteTopicController _instance = KiteTopicController._();
  static KiteTopicController get globalInstance => _instance;

  KiteTopicController._() {
    _topicList.addAll(KiteTopicEntity.getDefaultKiteTopics());
    _discussionList.addAll(
      KiteTopicDiscussionEntity.getDefaultTopicDiscussions(),
    );
    _likeRelationshipList.addAll(KiteTopicLikeEntity.getDefaultTopicLikes());
    _refreshTopicDiscussionCounts();
  }

  /// 话题数据列表
  final List<KiteTopicEntity> _topicList = [];

  /// 讨论数据列表
  final List<KiteTopicDiscussionEntity> _discussionList = [];

  /// 点赞关系数据列表
  final List<KiteTopicLikeEntity> _likeRelationshipList = [];

  /// 当前选中的话题
  final ReactiveValueNotifier<KiteTopicEntity?> _currentTopic =
      ReactiveValueNotifier<KiteTopicEntity?>(null);

  /// 当前话题的讨论列表
  final ReactiveValueNotifier<List<KiteTopicDiscussionEntity>>
  _currentTopicDiscussions =
      ReactiveValueNotifier<List<KiteTopicDiscussionEntity>>([]);

  /// 用户参与讨论的话题列表
  final ReactiveValueNotifier<List<KiteTopicEntity>> _userDiscussedTopics =
      ReactiveValueNotifier<List<KiteTopicEntity>>([]);

  /// 所有话题列表
  final ReactiveValueNotifier<List<KiteTopicEntity>> _allTopics =
      ReactiveValueNotifier<List<KiteTopicEntity>>([]);

  /// 点赞状态映射表 (discussionId 映射到 ReactiveValueNotifier)
  final Map<String, ReactiveValueNotifier<bool>> _likeStatusMap = {};

  // 状态访问器
  ReactiveValueNotifier<KiteTopicEntity?> get currentTopicState =>
      _currentTopic;
  ReactiveValueNotifier<List<KiteTopicDiscussionEntity>>
  get currentTopicDiscussionsState => _currentTopicDiscussions;
  ReactiveValueNotifier<List<KiteTopicEntity>> get userDiscussedTopicsState =>
      _userDiscussedTopics;
  ReactiveValueNotifier<List<KiteTopicEntity>> get allTopicsState => _allTopics;

  /// 发表话题讨论
  bool publishTopicDiscussion({
    required String topicId,
    required String discussionContent,
  }) {
    final currentUser =
        PersonaSessionController.globalInstance.currentPersonaState.value;
    if (currentUser == null || discussionContent.trim().isEmpty) return false;

    try {
      final newDiscussion = KiteTopicDiscussionEntity(
        uniqueIdentifier:
            'topic_discussion_${DateTime.now().millisecondsSinceEpoch}',
        topicIdentifier: topicId,
        publisherPersonaId: currentUser.uniqueIdentifier,
        discussionTextContent: discussionContent.trim(),
        publishTimestamp: DateTime.now(),
        totalLikeCount: 0,
      );

      _discussionList.insert(0, newDiscussion);
      _updateTopicDiscussionCount(topicId);

      // 如果当前正在查看这个话题，刷新讨论列表
      if (_currentTopic.value?.uniqueIdentifier == topicId) {
        getTopicDiscussions(topicId);
      }

      _refreshUserDiscussedTopics();
      return true;
    } catch (e) {
      return false;
    }
  }

  /// 获取话题下的所有讨论
  List<KiteTopicDiscussionEntity> getTopicDiscussions(String topicId) {
    try {
      final discussions =
          _discussionList
              .where((discussion) => discussion.topicIdentifier == topicId)
              .toList();

      discussions.sort(
        (a, b) => b.publishTimestamp.compareTo(a.publishTimestamp),
      );

      // 更新点赞数
      for (int i = 0; i < discussions.length; i++) {
        final likeCount = _getLikeCountForDiscussion(
          discussions[i].uniqueIdentifier,
        );
        discussions[i] = discussions[i].duplicateWithModifications(
          totalLikeCount: likeCount,
        );
      }

      _currentTopicDiscussions.value = discussions;
      return discussions;
    } catch (e) {
      _currentTopicDiscussions.value = [];
      return [];
    }
  }

  /// 获取用户参与讨论过的话题列表
  List<KiteTopicEntity> getUserDiscussedTopics() {
    final currentUser =
        PersonaSessionController.globalInstance.currentPersonaState.value;
    if (currentUser == null) {
      _userDiscussedTopics.value = [];
      return [];
    }

    try {
      final userDiscussions =
          _discussionList
              .where(
                (discussion) =>
                    discussion.publisherPersonaId ==
                    currentUser.uniqueIdentifier,
              )
              .toList();

      final discussedTopicIds =
          userDiscussions.map((d) => d.topicIdentifier).toSet();

      final discussedTopics =
          _topicList
              .where(
                (topic) => discussedTopicIds.contains(topic.uniqueIdentifier),
              )
              .toList();

      discussedTopics.sort(
        (a, b) => b.creationTimestamp.compareTo(a.creationTimestamp),
      );
      _userDiscussedTopics.value = discussedTopics;
      return discussedTopics;
    } catch (e) {
      _userDiscussedTopics.value = [];
      return [];
    }
  }

  /// 获取所有话题列表
  List<KiteTopicEntity> getAllTopics() {
    final sortedTopics = List<KiteTopicEntity>.from(_topicList);
    sortedTopics.sort(
      (a, b) => b.creationTimestamp.compareTo(a.creationTimestamp),
    );
    _allTopics.value = sortedTopics;
    return sortedTopics;
  }

  /// 点赞讨论
  bool likeDiscussion(String discussionId) {
    final currentUser =
        PersonaSessionController.globalInstance.currentPersonaState.value;
    if (currentUser == null) return false;

    try {
      // 检查是否已经点赞
      final existingLike = _likeRelationshipList.firstWhere(
        (like) =>
            like.discussionIdentifier == discussionId &&
            like.likerPersonaId == currentUser.uniqueIdentifier &&
            like.activeLikeStatus,
        orElse: () => KiteTopicLikeEntity.createEmptyInstance(),
      );

      if (existingLike.uniqueIdentifier.isNotEmpty) {
        return false; // 已经点赞了
      }

      final newLike = KiteTopicLikeEntity(
        uniqueIdentifier: 'topic_like_${DateTime.now().millisecondsSinceEpoch}',
        discussionIdentifier: discussionId,
        likerPersonaId: currentUser.uniqueIdentifier,
        likeTimestamp: DateTime.now(),
        activeLikeStatus: true,
      );

      _likeRelationshipList.add(newLike);
      _updateLikeStatus(discussionId, currentUser.uniqueIdentifier);

      // 刷新当前话题讨论列表
      if (_currentTopic.value != null) {
        getTopicDiscussions(_currentTopic.value!.uniqueIdentifier);
      }

      return true;
    } catch (e) {
      return false;
    }
  }

  /// 取消点赞讨论
  bool unlikeDiscussion(String discussionId) {
    final currentUser =
        PersonaSessionController.globalInstance.currentPersonaState.value;
    if (currentUser == null) return false;

    try {
      final likeIndex = _likeRelationshipList.indexWhere(
        (like) =>
            like.discussionIdentifier == discussionId &&
            like.likerPersonaId == currentUser.uniqueIdentifier &&
            like.activeLikeStatus,
      );

      if (likeIndex == -1) return false; // 没有点赞记录

      final updatedLike = _likeRelationshipList[likeIndex]
          .duplicateWithModifications(activeLikeStatus: false);

      _likeRelationshipList[likeIndex] = updatedLike;
      _updateLikeStatus(discussionId, currentUser.uniqueIdentifier);

      // 刷新当前话题讨论列表
      if (_currentTopic.value != null) {
        getTopicDiscussions(_currentTopic.value!.uniqueIdentifier);
      }

      return true;
    } catch (e) {
      return false;
    }
  }

  /// 删除话题讨论
  bool deleteTopicDiscussion(String discussionId) {
    try {
      final discussionIndex = _discussionList.indexWhere(
        (discussion) => discussion.uniqueIdentifier == discussionId,
      );

      if (discussionIndex == -1) return false; // 讨论不存在

      final discussion = _discussionList[discussionIndex];
      final topicId = discussion.topicIdentifier;

      // 删除讨论
      _discussionList.removeAt(discussionIndex);

      // 删除相关的点赞记录
      _likeRelationshipList.removeWhere(
        (like) => like.discussionIdentifier == discussionId,
      );

      // 清理点赞状态映射
      _likeStatusMap.removeWhere(
        (key, value) => key.startsWith('${discussionId}_'),
      );

      // 更新话题讨论数量
      _updateTopicDiscussionCount(topicId);

      // 如果当前正在查看这个话题，刷新讨论列表
      if (_currentTopic.value?.uniqueIdentifier == topicId) {
        getTopicDiscussions(topicId);
      }

      _refreshUserDiscussedTopics();
      return true;
    } catch (e) {
      return false;
    }
  }

  /// 获取讨论的点赞状态
  ReactiveValueNotifier<bool> getDiscussionLikeStatus(String discussionId) {
    final currentUser =
        PersonaSessionController.globalInstance.currentPersonaState.value;
    if (currentUser == null) {
      return ReactiveValueNotifier<bool>(false);
    }

    final statusKey = '${discussionId}_${currentUser.uniqueIdentifier}';
    if (!_likeStatusMap.containsKey(statusKey)) {
      _likeStatusMap[statusKey] = ReactiveValueNotifier<bool>(false);
      _updateLikeStatus(discussionId, currentUser.uniqueIdentifier);
    }
    return _likeStatusMap[statusKey]!;
  }

  /// 选择当前话题
  void selectTopic(String topicId) {
    try {
      final topic = _topicList.firstWhere(
        (topic) => topic.uniqueIdentifier == topicId,
      );
      _currentTopic.value = topic;
      getTopicDiscussions(topicId);
    } catch (e) {
      _currentTopic.value = null;
      _currentTopicDiscussions.value = [];
    }
  }

  /// 获取讨论的点赞数
  int _getLikeCountForDiscussion(String discussionId) {
    return _likeRelationshipList
        .where(
          (like) =>
              like.discussionIdentifier == discussionId &&
              like.activeLikeStatus,
        )
        .length;
  }

  /// 更新点赞状态
  void _updateLikeStatus(String discussionId, String userId) {
    final statusKey = '${discussionId}_$userId';
    if (_likeStatusMap.containsKey(statusKey)) {
      final isLiked = _likeRelationshipList.any(
        (like) =>
            like.discussionIdentifier == discussionId &&
            like.likerPersonaId == userId &&
            like.activeLikeStatus,
      );
      _likeStatusMap[statusKey]!.value = isLiked;
    }
  }

  /// 更新话题讨论数量
  void _updateTopicDiscussionCount(String topicId) {
    final topicIndex = _topicList.indexWhere(
      (topic) => topic.uniqueIdentifier == topicId,
    );
    if (topicIndex != -1) {
      final discussionCount =
          _discussionList
              .where((discussion) => discussion.topicIdentifier == topicId)
              .length;

      final updatedTopic = _topicList[topicIndex].duplicateWithModifications(
        totalDiscussionCount: discussionCount,
      );
      _topicList[topicIndex] = updatedTopic;

      if (_currentTopic.value?.uniqueIdentifier == topicId) {
        _currentTopic.value = updatedTopic;
      }
    }
  }

  /// 刷新所有话题的讨论数量
  void _refreshTopicDiscussionCounts() {
    for (int i = 0; i < _topicList.length; i++) {
      final topicId = _topicList[i].uniqueIdentifier;
      final discussionCount =
          _discussionList
              .where((discussion) => discussion.topicIdentifier == topicId)
              .length;

      _topicList[i] = _topicList[i].duplicateWithModifications(
        totalDiscussionCount: discussionCount,
      );
    }
  }

  /// 刷新用户讨论话题列表
  void _refreshUserDiscussedTopics() {
    getUserDiscussedTopics();
  }

  /// 静态方法：快速发表讨论
  static bool quickPublishDiscussion({
    required String topicId,
    required String discussionContent,
  }) {
    return globalInstance.publishTopicDiscussion(
      topicId: topicId,
      discussionContent: discussionContent,
    );
  }

  /// 静态方法：快速点赞讨论
  static bool quickLikeDiscussion(String discussionId) {
    return globalInstance.likeDiscussion(discussionId);
  }

  /// 静态方法：快速取消点赞讨论
  static bool quickUnlikeDiscussion(String discussionId) {
    return globalInstance.unlikeDiscussion(discussionId);
  }
}
